<template>
    <view class="content" :style="{height:`calc(100vh - ${tabbarHeight}upx)`}">
        <view class="top-desp-nav">
            <view class="desp-title">
                <text>AI</text>
                <text>工作流助手</text>
            </view>
        </view>

        <view class="content-contain">
            <template v-for="(item,index) in dictionaryInfo">
                <uni-transition :show="true" :mode-class="['slide-bottom','zoom-in']"
                                :styles="{display:'flex',justifyContent:item.showType == 0 ? 'flex-end' : 'flex-start',minHeight:'96upx',alingItems:'center'}">
                    <messageTip :show-type="item.showType" :infoSet="item.infoSet"></messageTip>
                </uni-transition>
            </template>
        </view>
        <template v-if="isThinkStart">
            <uni-transition :show="true" :mode-class="['fade']">
                <view class="think-deeply">
                    <view class="throk-cont">正在思考</view>
                    <image src="/static/images/load.gif" class="sikaoWidth"></image>
                </view>
            </uni-transition>
        </template>
        <view :style="{height:(inputHeight+tabbarHeight+180)+'upx'}"></view>
        <view class="foot-content" :style="{bottom:tabbarHeight - 2 +'upx'}">
            <view class="search-cont">
                <view v-if="uploadFile.length"
                      style="margin-bottom: 20upx;display: flex;align-items: center;flex-wrap: wrap">
                    <template v-for="item in uploadFile">
                        <view v-if="item.name.includes('.doc') || item.name.includes('.doc')"
                              style="display: flex;align-items: center;margin-right: 20upx">
                            <image src="/static/docx.png" style="width: 40upx;height: 40upx"></image>
                            <text style="margin-left: 20upx">{{ item.name }}</text>
                        </view>
                        <view v-else-if="item.name.includes('.pdf')"
                              style="display: flex;align-items: center;margin-right: 20upx">
                            <image src="/static/pdf.png" style="width: 40upx;height: 40upx"></image>
                            <text style="margin-left: 20upx">{{ item.name }}</text>
                        </view>
                        <view v-else
                              style="display: flex;align-items: center;margin-right: 20upx">
                            <image src="/static/tupian.png" style="width: 40upx;height: 40upx"></image>
                            <text style="margin-left: 20upx">{{ item.name }}</text>
                        </view>
                    </template>

                </view>
                <textarea class="search-input" placeholder="有什么问题快来问我吧" placeholder-class="sear-place-cont"
                          confirm-type="search" :auto-height="true" :fixed="true" :maxlength="-1"
                          v-model="formObj.content"
                          @linechange="linechangeInput"/>

                <view class="footer-send">
                    <view>
                        <image src="@/static/images/shangchuan.png" style="width: 60upx;height: 60upx"
                               @click="uploadFileImage"></image>
                    </view>
                    <view style="display: flex;align-items: center">
                        <!--                        <text class="iconfont icon-maikefeng" style="font-size: 36upx"></text>-->
                        <!--                        <text style="margin: 0 20upx">|</text>-->
                        <view style="width: 60upx;height: 60upx;border-radius: 50%;display: flex;align-items: center;justify-content: center"
                              :style="{background:(formObj.content && !isThinkStart) || (uploadFile.length && !isThinkStart) ? '#4D57F9' : '#eee'}">
                            <image src="@/static/images/fasong.png" style="width: 30upx;height: 30upx"
                                   v-if="(!formObj.content && !uploadFile.length) || isThinkStart"></image>
                            <image src="@/static/images/fasong1.png"
                                   style="width: 30upx;height: 30upx"
                                   v-else-if="(formObj.content && !isThinkStart) || (uploadFile.length && !isThinkStart)"
                                   @click="sendInfo"></image>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import messageTip from "@/components/message-tip/index.vue";
import despShopRecom from "@/components/desp-shop-recom/index.vue";
import {uploadUrl, fileOpenUrl} from '@/config'
import {toast} from '@/utils/common'
import {getToken} from '@/utils/auth'
import {breakOriginRequirest} from '@/utils/request'

let flowSet = {
    message: '',
}
export default {
    components: {
        messageTip,
        despShopRecom
    },
    data() {
        return {
            tabbarHeight: 0,
            isThinkStart: false,
            formObj: {
                content: '',
                fileImageSet: [],
            },
            inputHeight: 101,
            dictionaryInfo: [],
            uploadFile: [],
            user: '',

        }
    },
    onLoad() {
        this.formObj.content = `审查主体{填写内容}工作领域{填写内容}合同要点{填写内容}`
        this.uploadFile = []
        this.dictionaryInfo = []
        this.dictionaryInfo.push({
            showType: '1',
            infoSet: [
                {
                    type: 'message',
                    message: '你好呀！我是你的AI工作流助手，有什么需要帮忙的尽管说～ 😊'
                }
            ]
        })
    },
    mounted() {
        // 获取系统信息
        let systemInfo = uni.getSystemInfoSync();
        this.tabbarHeight = systemInfo.windowBottom * 2
    },
    methods: {

        breakOrigin() {
            this.isThinkStart = false
            breakOriginRequirest()
        },
        screenHeight() {
            let _that = this
            let query = uni.createSelectorQuery();
            let dom = query.select('.foot-content');
            this.$nextTick(() => {
                dom.boundingClientRect(function (res) {
                    console.log(res, 'res')
                    if (res.height <= 105) {
                        _that.inputHeight = 101
                    } else {
                        _that.inputHeight = res.height * 2 - 100
                    }
                }).exec();
            })
        },
        linechangeInput() {
            setTimeout(() => {
                this.screenHeight()
            }, 500)
        },
        sendInfo() {
            if (!this.uploadFile.length) {
                toast('请上传需要审查的文件主体')
                return;
            }
            let text = this.formObj.content
            const regex = /\{([^}]*)\}/g;
            let matches;
            const contents = [];
            while ((matches = regex.exec(text)) !== null) {
                contents.push(matches[1]); // matches[1] 就是花括号里的内容
            }
            for (let val of contents) {
                if (val == '请填写内容') {
                    toast('请注意内容格式')
                    return
                }
            }
            // data主体
            const data = {
                apart: contents[0],
                workField: contents[1],
                attention: contents[2]
            }
            this.formObj.fileImageSet = [...this.uploadFile]
            console.log(this.formObj.fileImageSet, 'this.formObj.fileImageSet')
            //把自己说的话加入到聊天中
            this.dictionaryInfo.push({
                showType: '0',
                infoSet: [
                    {
                        message: this.formObj.fileImageSet,
                        type: 'image'
                    },
                    {
                        message: this.formObj.content,
                        type: 'message'
                    }
                ]
            })
            data.user = this.user
            this.isThinkStart = true
            const userId = uni.getStorageSync('storage_data').user_id
            const eventCloneSource = new EventSource(`${uploadUrl}/agent/workflow/runWorkFlow?apart=${data.apart}&workField=${data.workField}
               &attention=${data.attention}&user=${data.user}&userId=${userId}`)
            eventCloneSource.addEventListener('open', () => {
                console.log('打开了连接')
            })
            eventCloneSource.addEventListener('message', (res) => {
                const data = JSON.parse(res.data)
                if (data.data.title == '结束') {
                    if (data.data.hasOwnProperty('outputs')) {
                        flowSet.message = ''
                        flowSet.message = flowSet.message + data.data.outputs['审查结果']
                        let fileSetArr = []
                        console.log(data.data.outputs, 'data.data.outputs')
                        if (data.data.outputs.hasOwnProperty('DOCX')) {
                            const docxData = data.data.outputs['DOCX'][0]
                            fileSetArr.push({
                                name: docxData.filename,
                                url: fileOpenUrl + docxData.url
                            })
                        }
                        if (data.data.outputs.hasOwnProperty('DOC')) {
                            const docxData = data.data.outputs['DOC'][0]
                            fileSetArr.push({
                                name: docxData.filename,
                                url: fileOpenUrl + docxData.url
                            })
                        }
                        if (data.data.outputs.hasOwnProperty('PDF')) {
                            const docxData = data.data.outputs['PDF'][0]
                            fileSetArr.push({
                                name: docxData.filename,
                                url: fileOpenUrl + docxData.url
                            })
                        }
                        console.log(fileSetArr, 'fileSetArr')
                        this.dictionaryInfo.push({
                            showType: '1',
                            infoSet: [
                                {
                                    message: flowSet.message,
                                    type: res.event || 'message',
                                    fileSetArr: fileSetArr
                                }
                            ]
                        })
                        this.isThinkStart = false
                        this.formObj.content = '审查主体{填写内容}工作领域{填写内容}合同要点{填写内容}'
                        this.formObj.fileImageSet = []
                        this.uploadFile = []
                        eventCloneSource.close()
                    }
                }
            })
            eventCloneSource.addEventListener('error', () => {
                eventCloneSource.close()
                this.isThinkStart = false
                toast('请求体连接意外关闭，请重新发送')
            })
            return;
        },
        uploadFileImage() {
            let file = []
            uni.chooseFile({
                type: "all",
                extension: ['.doc', '.docx', '.pdf'],
                count: 1,
                success: (result) => {
                    file = result.tempFilePaths
                    uni.showLoading({
                        title: '文件上传中',
                        mask: true
                    })
                    uni.uploadFile({
                        url: uploadUrl + '/agent/workflow/upload',
                        filePath: file[0],
                        name: 'file',
                        header: {
                            Authorization: 'Bearer ' + getToken()
                        },
                        timeout: 50000,
                        success: (resimg) => {
                            if (resimg.statusCode == 200) {
                                const data = JSON.parse(resimg.data)
                                this.user = data.id
                                this.uploadFile.push(result.tempFiles[0])
                                this.uploadFile[this.uploadFile.length - 1].imageId = data.id
                            } else {
                                toast('文件上传失败请稍后再试')
                            }
                        },
                        fail: (err) => {
                            toast(err || '文件上传失败请稍后再试')
                        },
                        complete: () => {
                            uni.hideLoading()
                        }
                    })
                }
            })
        }
    }
}
</script>
<style scoped lang="scss">
.content {
  width: 100%;
  background: linear-gradient(180deg, #DCDCFE 0%, #F1F4F5 100%);
  position: relative;
  padding-top: 190upx;
  overflow-y: auto;

  .top-desp-nav {
    width: 100%;
    height: 180upx;
    background: #fff;
    border-bottom-left-radius: 80upx;
    border-bottom-right-radius: 80upx;
    margin-bottom: 8upx;
    //position: relative;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 10;

    .desp-title {
      position: absolute;
      bottom: 20upx;
      left: 60upx;
      font-family: YouSheBiaoTiHei, YouSheBiaoTiHei;
      font-size: 40upx;
      font-weight: 600;

      & > text:first-child {
        //font-style: italic;
        background: linear-gradient(
                        45deg, /* 渐变角度 */
                        rgb(60, 124, 252), /* 起始颜色 */
                        rgb(56, 139, 254) /* 结束颜色 */
        );
        -webkit-background-clip: text; /* 关键属性：背景裁剪为文本 */
        background-clip: text;
        color: transparent; /* 必须设置透明色 */
        margin-right: 4upx;
      }

      & > text:last-child {
        position: relative;

        &::before {
          content: '';
          display: inline-block;
          width: 50upx;
          height: 4upx;
          background: linear-gradient(149deg, #4D58F7 0%, #3798FF 100%);
          position: absolute;
          bottom: -7upx;
          left: -7upx;
        }
      }
    }
  }

  .content-contain {
    padding: 0 28upx;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    //margin-top: 180upx;
  }

  .foot-content {
    position: fixed;
    bottom: 4upx;
    left: 0;
    right: 0;
    z-index: 10;
    width: 100%;
    min-height: 200upx;
    background: #FFFFFF;
    box-shadow: 0px -2upx 8upx 0px rgba(54, 151, 253, 0.15);
    padding: 24upx 28upx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;

    .search-cont {
      flex: 1;
      padding: 20upx;
      box-sizing: border-box;
      border-radius: 20upx;
      border: 2upx solid #EEEEEE;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: space-between;

      .search-input {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 28upx;
        color: #999;
      }

      .footer-send {
        width: 100%;
        margin-top: 40upx;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
  }

  .think-deeply {
    margin-top: 74upx;
    display: flex;
    align-items: center;
    padding: 0 28upx;

    .throk-cont {
      width: 152upx;
      height: 96upx;
      background: linear-gradient(90deg, #FFFFFF 0%, rgba(255, 255, 255, 0) 100%);
      box-shadow: 0px 0px 12upx 0px rgba(25, 140, 255, 0.25);
      border-radius: 40upx;
      border: 2upx solid #FFFFFF;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28upx;
      text-align: left;
      font-weight: 500;
      color: #4D57F9;
      margin-right: 20upx;
    }

    .stop-click {
      width: 96upx;
      height: 76upx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(90deg, #FFFFFF 0%, rgba(255, 255, 255, 0) 100%);
      box-shadow: 0px 0px 12upx 0px rgba(25, 140, 255, 0.25);
      border-radius: 40upx;
      border: 2upx solid #FFFFFF;
    }
  }
}

::v-deep .sear-place-cont {
  font-family: PingFang SC, PingFang SC;
  font-weight: 500;
  font-size: 28upx;
  color: rgba(102, 102, 102, 0.4);
}

::v-deep .search-input {
  width: 100%;
}

.sikaoWidth{
    width: 150upx;
    height: 150upx;
    position: relative;
    left: -35upx;
    top: 10upx;
}
</style>
